<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

class Push extends Model
{
    public $targetNum;//目标人数
    public $ids;//目标ID
    public $message_id;//消息模板
    public $condition;//所有用户的查询条件


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['targetNum','message_id'], 'integer'],
            [['ids','condition'], 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'targetNum' => '目标人数',
            'message_id' => '选择模板',
            'ids' => '目标人ID',
        ];
    }

    public function pushmessage()
    {
        $client = new \JPush\Client(Yii::$app->params['push']['app_key'], Yii::$app->params['push']['master_secret']);

        $messageModel = \app\models\Message::findOne($this->message_id);
        $ids = explode(',',$this->ids);
        if(in_array('all',$ids)) {
            if($this->condition) {
                $condition = json_decode($this->condition,true);
                $searchModel = new MemberSearch();
                $provider = $searchModel->search($condition);
                $provider->pagination = false;
                $aliases = array();
                foreach($provider->getModels() as $model) {
                    $aliases[] = $model->alias;
                }

                $client->push()
                    ->setPlatform('all')
                    ->addAlias($aliases)
                    ->setNotificationAlert($messageModel->theme)
                    ->send();

            } else {
                $client->push()
                    ->setPlatform('all')
                    ->addAllAudience()
                    ->setNotificationAlert($messageModel->theme)
                    ->send();
            }

        } else {

            $aliases = Member::find()->select('alias')->where(['in','id',$ids])->column();
            $client->push()
                ->setPlatform('all')
                ->addAlias($aliases)
                ->setNotificationAlert($messageModel->theme)
                ->send();
        }

        return true;
    }

}
